package com.phpxiu.app.view.custom;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.RelativeLayout;

import com.phpxiu.app.kkylive.KKYApp;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by 吴金洲 on 2016/7/11
 */
public class MPraiseAnimView extends RelativeLayout {
    private final static List<PraisePathAnimator> ANIMATOR_CACHE=new ArrayList<PraisePathAnimator>();
    private final static List<PraiseImageView>VIEW_CACHE=new ArrayList<PraiseImageView>();
    private int mWidth;//动画运行区域宽度
    private int mHeight;//动画运行区域高度
    private int mAnimViewWidth;//动画图形的宽度
    private int XRandomMax;
    private int pathStartX,pathStartY;//路径起始点
    private float bezierFirstY,bezierSecondY,bezierEndY;//贝塞尔曲线三个控制点的Y坐标
    private Random random=new Random();//X坐标的随机器
    private static AnimHandler animShowHandler;
    private MsgThread animMsgThread=new MsgThread();
    private static Handler animMsgThreadHandler;
    private List<String>anim=new ArrayList<String>();
    public MPraiseAnimView(Context context) {
        super(context);
        init();
    }
    public MPraiseAnimView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MPraiseAnimView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(21)
    public MPraiseAnimView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    /**
     * 初始化
     */
    private void init(){
        mAnimViewWidth= KKYApp.getInstance().HEART_SHAPE_SIZE;
        if(animMsgThread!=null){
            animMsgThread.start();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取本身的宽高 这里要注意,测量之后才有宽高
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        pathStartX=(mWidth-mAnimViewWidth)/2;
        XRandomMax=mWidth-mAnimViewWidth+5;
        pathStartY=mHeight-mAnimViewWidth;
        bezierFirstY=mHeight*0.7f;
        bezierSecondY=mHeight*0.3f;
        bezierEndY=mAnimViewWidth/2;
    }

    private Path createAnimPath(){
        int bezierFirstX=mAnimViewWidth+random.nextInt(XRandomMax);
        int bezierSecondX=mAnimViewWidth+random.nextInt(XRandomMax);
        int bezierEndX=mAnimViewWidth+random.nextInt(XRandomMax);
        Path path=new Path();
        path.moveTo(pathStartX,pathStartY);
        path.cubicTo(bezierFirstX,bezierFirstY,bezierSecondX,bezierSecondY,bezierEndX,bezierEndY);
        return path;
    }

    /**
     * 播放动画，动画图形颜色
     * @param color
     */
    public void play(String color){
        PraiseImageView view=new PraiseImageView(getContext());
        view.setImageBitmap(KKYApp.HEART_BITMAP_CACHE.get("heart_"+color));
        addView(view, KKYApp.HEART_VIEW_PARAM);
        PraisePathAnimator animator=new PraisePathAnimator(createAnimPath(),this,view);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.setDuration(3000+random.nextInt(800));
        view.startAnimation(animator);
    }


    /**
     * 批量播放
     * @param color 颜色
     * @param size 个数
     */
    public void playAnim(String color,int size) {
        if(animMsgThreadHandler==null)return;
        if(animShowHandler==null){
            animShowHandler=new AnimHandler(this);
        }
        Message msg;
        for (int i=0;i<size;i++){
            msg=animMsgThreadHandler.obtainMessage();
            msg.what= MsgThread.INSERT_MSG;
            msg.obj=color;
            animMsgThreadHandler.sendMessage(msg);
        }
    }

    private void read(){
        if(anim.size()>0) {
            Message msg = animShowHandler.obtainMessage();
            msg.what = AnimHandler.PLAY_ANIM;
            msg.obj = anim.get(0);
            anim.remove(0);
            animShowHandler.sendMessage(msg);
        }
    }

    /**
     * 延时动画消息分发处理器
     */
    public class AnimHandler extends Handler {
        public final static int PLAY_ANIM = 1;
        WeakReference<MPraiseAnimView> viewWeak;
        public AnimHandler(MPraiseAnimView animView) {
            viewWeak = new WeakReference<MPraiseAnimView>(animView);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MPraiseAnimView animView = viewWeak.get();
            if (animView == null) return;
            switch (msg.what) {
                case PLAY_ANIM:
                    play(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    }

    public void destroy(){
        if(animMsgThread!=null){
            animMsgThread.stopLoop();
            animMsgThread=null;
        }
        if(animShowHandler!=null){
            animShowHandler.removeCallbacksAndMessages(null);
            animShowHandler=null;
        }
        anim.clear();
    }

    class MsgThread extends Thread{
        public final static int READ_MSG=0x1;
        public final static int INSERT_MSG=0x2;
        private Looper mLooper;
        private Timer readMsgTimer=new Timer(true);
        private TimerTask readMsgTask;
        MsgThread() {
            readMsgTask=new TimerTask() {
                @Override
                public void run() {
                    if(animMsgThreadHandler!=null){
                        animMsgThreadHandler.sendEmptyMessage(READ_MSG);
                    }
                }
            };
        }

        @Override
        public void run() {
            readMsgTimer.schedule(readMsgTask,0,100);//100毫秒显示一个泡泡
            Looper.prepare();
            mLooper=Looper.myLooper();
            animMsgThreadHandler=new Handler(mLooper){
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what){
                        case READ_MSG:
                            read();
                            break;
                        case INSERT_MSG:
                            anim.add(msg.obj.toString());
                            break;
                        default:
                            break;
                    }
                }
            };
            Looper.loop();
        }

        public void stopLoop(){
            if(readMsgTimer!=null){
                readMsgTimer.cancel();
                readMsgTimer=null;
            }
            if(readMsgTask!=null){
                readMsgTask.cancel();
                readMsgTask=null;
            }
            if(animMsgThreadHandler!=null){
                animMsgThreadHandler.removeCallbacksAndMessages(null);
            }
            if(mLooper!=null){
                mLooper.quit();
            }
        }
    }

    /**
     * 路径动画器
     */
    public class PraisePathAnimator extends Animation implements Animation.AnimationListener{
        private PathMeasure mPathMeasure;
        private PraiseImageView mView;
        private float mDistance;
        private boolean isEnd=true;
        private long mTime;
        public PraisePathAnimator(Path path,View parent, PraiseImageView praiseImageView) {
            mPathMeasure = new PathMeasure(path,false);//如果为true，则只在容器内
            mDistance = mPathMeasure.getLength();
            mView = praiseImageView;
            parent.setLayerType(View.LAYER_TYPE_HARDWARE,null);
            setAnimationListener(this);
        }

        @Override
        protected void applyTransformation(float factor, Transformation transformation) {
            Matrix matrix = transformation.getMatrix();
            mPathMeasure.getMatrix(mDistance * factor, matrix, PathMeasure.POSITION_MATRIX_FLAG);
            float scale = 1F;
            if (mTime * factor < 300.0F) {
                scale = scale(factor, 0.0D, 0.06666667014360428D, 0.20000000298023224D, 1.100000023841858D);
            } else if (mTime * factor < 400.0F) {
                scale = scale(factor, 0.06666667014360428D, 0.10000000149011612D, 1.100000023841858D, 1.0D);
            }
            mView.setScaleX(scale);
            mView.setScaleY(scale);
            transformation.setAlpha(1.0F - factor);
        }

        @Override
        public void setDuration(long durationMillis) {
            super.setDuration(durationMillis);
            mTime=durationMillis;
        }

        /**
         * 更改颜色
         * @param view
         */
        public void updateColor(PraiseImageView view){
            mView=view;
        }

        public boolean isEnd() {
            return isEnd;
        }

        public void setEnd(boolean isEnd) {
            this.isEnd = isEnd;
        }

        @Override
        public void onAnimationStart(Animation animation) {
            this.isEnd=false;
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            this.isEnd=true;
            removeView(mView);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    }

    private static float scale(double a, double b, double c, double d, double e) {
        return (float) ((a - b) / (c - b) * (e - d) + d);
    }
}
